﻿/*
Creator: vanduong
*/
var pagingManager;
var totalPage = 10;
var pageSize = 10;
var pageIndex = 0;

var enumCode = "";
var fullName = "";
var userName = "";
var groupCode = "";

function createPage() {
    pageIndex = 0;
    pagingManager = new PagingEvent("pagingContainer2");
    pagingManager.setNextClassName("clsPage");
    pagingManager.setPreviousClassName("clsPage");
    pagingManager.setPageClassName("clsPage");
    pagingManager.setFirstClassName("clsPage");
    pagingManager.setLastClassName("clsPage");
    pagingManager.setSelectedColor("black");
    pagingManager.setFirstLastNextPreviousColor("#428BCA");
    pagingManager.setPageColor("#428BCA");
    pagingManager.setTotalPage(totalPage);
    pagingManager.setEvent(previous_click, page_click, next_click, first_click, last_click);
    pagingManager.create();
    pagingManager.setCurrentPage(pageIndex);
    setSate(pageIndex);
}

function storePaging() {
    var newParent = document.getElementById('pagingContainer2');
    var oldParent = document.getElementById('pagingContainer');

    moveElement(oldParent, newParent);
}

function restorePaging() {
    var newParent = document.getElementById('pagingContainer');
    var oldParent = document.getElementById('pagingContainer2');

    moveElement(oldParent, newParent);
}

function moveElement(oldParent, newParent) {
    if (oldParent == null || newParent == null) {
        return;
    }

    while (oldParent.childNodes.length > 0) {
        newParent.appendChild(oldParent.childNodes[0]);
    }
}

$(document).ready(function () {
    token = $('[name=__RequestVerificationToken]').val();
    $("#btnSearch").on("click", btnSearch_click);
    $("input").on("keypress", function (event) {
        if (event.which == 13) {
            btnSearch_click();
        }
    });
    $("#inExcel").click(function () {
        var searchInfo = getSearchInfo(0, 9999);
        window.location.href = urlPrintExcel + '?GROUP_CODE=' + searchInfo.GroupCode +
            '&FULL_NAME=' + searchInfo.FullName +
            '&USERNAME=' + searchInfo.UserName +
            '#ENUM_CODE' + searchInfo.EnumCode;
    });

    $("#btnPrint").click(function () {
        var searchInfo = getSearchInfo(0, 9999);
        var frame = $('<iframe src="' + urlPrintEnum + '?GROUP_CODE=' + searchInfo.GroupCode +
            '&FULL_NAME=' + searchInfo.FullName +
            '&USERNAME=' + searchInfo.UserName +
            '#ENUM_CODE' + searchInfo.EnumCode + '" frameborder="0"></iframe>');
        $('#divPrintEnum').html(frame);
        return false;
    });

    pageIndex = 0;
    $(window).load(function () {
        var totalRecord = recordCount;
        totalPage = getTotal(totalRecord, pageSize);
        createPage();
        addTableFooter();
        addRecordInfo(totalRecord, startRecord, endRecord);
        if (hasManyPage()) {
            restorePaging();
        }
        pagingManager.setTotalPage(totalPage);
    });   
});

function addTableFooter() {   
    var table = document.getElementById("EnumGrid");
    var footer = table.createTFoot();
    var row = footer.insertRow(0);
    row.id = "enum_footer";
    row.className = "webgrid-row-style";
    var cell = row.insertCell(0);
    cell.colSpan = 7;
    cell.innerHTML = "<div id='pagingContainer'></div>";
    cell.className = "classNameCSS";
    cell.id = "enum_footer_col";
}

function btnSearch_click() {
    storeSearchInfo();
    pageIndex = 0;
    action(pageIndex, pageSize);
}

function first_click() {
    if (pageIndex > 0) {
        pageIndex = 0;
        action(pageIndex, pageSize);
        //setSate(pageIndex, totalPage);
    }
}

function last_click() {
    if (pageIndex < totalPage - 1) {
        pageIndex = totalPage - 1;
        action(pageIndex, pageSize);
        //setSate(pageIndex, totalPage);
    }
}

function next_click() {
    if (pageIndex < totalPage - 1) {
        pageIndex++;
        action(pageIndex, pageSize);
        //setSate(pageIndex, totalPage);
    }
}

function page_click(event) {
    var dataIndex = document.getElementById(event.target.id);
    var index = parseInt(dataIndex.getAttribute("data-index"),10);
    if (index == pageIndex) {
        return;
    }
    pageIndex = index;
    action(pageIndex, pageSize);
   // setSate(pageIndex, totalPage);
}

function previous_click() {
    if (pageIndex > 0) {
        pageIndex--;
        action(pageIndex, pageSize);
        //setSate(pageIndex, totalPage);
    }
}

function setSate(pageIndex, totalPage) {
    if (pageIndex < 0 || pageIndex >= totalPage || totalPage == 0) {
        return;
    }
    if (pageIndex == 0) {
        pagingManager.HidePreviousFirstButton(true);
        pagingManager.HideNextLastButton(false);
    }
    else if (pageIndex == (totalPage - 1)) {
        pagingManager.HidePreviousFirstButton(false);
        pagingManager.HideNextLastButton(true);
    }
    else if (pageIndex > 0) {
        pagingManager.HidePreviousFirstButton(false);
        pagingManager.HideNextLastButton(false);
    }
}

function action(pageIndex, pageSize) {
    var seachrInfo = getSearchInfo(pageIndex, pageSize);
    search(seachrInfo);
    setTimeout(function () {
        pagingManager.setCurrentPage(pageIndex);       
        setSate(pageIndex, totalPage);
    }, 250);
}

function getSearchInfo(pageIndex, pageSize) {
    var adminCode = $("#ADMIN_CODE").val();

    return {
        AdminCode: adminCode,
        EnumCode: enumCode,
        FullName: fullName,
        UserName: userName,
        GroupCode: groupCode,
        PageIndex: pageIndex,
        PageSize: pageSize
    };
}

function storeSearchInfo() {
    //enumCode = $("#ENUM_CODE").val();
    fullName = $("#FULL_NAME_SEARCH").val();
    userName = $("#USERNAME_SEARCH").val();
    groupCode = $('#GROUPCODE_SEARCH option:selected').val();
}

function resetSearchInfoToDefault() {
    enumCode = "";
    fullName = "";
    userName = "";
    groupCode = "";
}

function hasManyPage() {
    if (totalPage > 1) {
        return true;
    }

    return false;
}

var token; 

function search(info) {
    storePaging();
    $("#divLoading").show();
    var ajax = $.ajax({
        cache: false,
        url: 'SearchResult',
        type: 'POST',
        headers: headers, //{'VerificationToken': token},
        data: {
            ADMIN_CODE: info.AdminCode,
            ENUM_CODE: info.EnumCode,
            FULL_NAME: info.FullName,
            USERNAME: info.UserName,
            GROUPCODE: info.GroupCode,
            PAGE_INDEX: info.PageIndex,
            PAGE_SIZE: info.PageSize
        },
        success: function (dataResult) {           
            $("#gridContent").html(dataResult);
        },
        error: function (ex) {
            alert("Co loi xay ra: \n" + JSON.stringify(ex));
        },
        complete: function () {
            $("#divLoading").hide();
            setTimeout(function () {
                var totalRecord = recordCount;
                totalPage = getTotal(totalRecord, pageSize);
                addTableFooter();                
                addRecordInfo(totalRecord, startRecord, endRecord);
                if (hasManyPage()) {
                    restorePaging();
                }
                pagingManager.setTotalPage(totalPage);
            }, 0);            
            $('[data-toggle="tooltip"]').tooltip();
        }
    });
}

function addRecordInfo(totalRecord, start, end) {
    var footerCell = document.getElementById("enum_footer_col");    
    footerCell.innerHTML += "<div style = 'float: right;'>Đang xem " + start + " - " + end + " trên " + totalRecord + " bản ghi </div>";
}

function getTotal(total, pageSize) {
    if (total % pageSize == 0) {
        return (total / pageSize);
    }

    return (Math.floor(total / pageSize) + 1);
}

var numOfRecord = 0;
function onDelete(id) {
    $("#divLoading").show();
    var info = getSearchInfo(pageIndex, pageSize);
    $.ajax({
        url: 'ViewForDelete',
        data: {
            "ENUMERATOR_ID": id,
            "Admin": "admin"
        },
        type: 'POST',
        success: function (data) {
            $("#divLoading").hide();
            var box = bootbox.dialog({
                title: "Xóa cán bộ nghiệp vụ",
                message: data,
                onEscape: function () {
                    box.modal('hide');
                },
                buttons: {
                    success: {
                        label: "<i class='fa fa-warning'></i> Xóa",
                        className: "btn btn-sm btn-danger", //btn-success
                        callback: function () {
                            //alert(id);
                            $("#divLoading").show();
                            $.ajax({
                                url: 'Delete_Record',
                                headers: headers,
                                data: {
                                    "id": id,
                                    ENUMERATOR_ID: id,
                                    ADMIN_CODE: info.AdminCode,
                                    ENUM_CODE: info.EnumCode,
                                    FULL_NAME: info.FullName,
                                    USERNAME: info.UserName,
                                    GROUPCODE: info.GroupCode,
                                    PAGE_INDEX: info.PageIndex,
                                    PAGE_SIZE: info.PageSize
                                },
                                //dataType: 'json',
                                type: 'post',
                                success: function (result) {
                                    Layout.toastr("", "Xóa thành công");                                    
                                    numOfRecord = result.RecordCount;
                                    pageIndex = result.PageIndex;
                                    totalPage = getTotal(numOfRecord, pageSize);
                                    pagingManager.setTotalPage(totalPage);
                                    action(pageIndex, pageSize);
                                },
                                complete: function () {
                                                                       
                                },
                                error: function (ex) {
                                    alert(JSON.stringify(ex));
                                }
                            });

                        }
                    },
                    danger: {
                        label: "<i class='fa fa-reply'></i> Hủy bỏ",
                        className: "btn btn-sm btn-default",//"btn-danger",
                        callback: function () {
                        }
                    }
                }
            });
        },
        complete: function () {
            $(".pm2-hidden").hide();
        }
    });
    return false;
}

function onCreate() {
    $("#divLoading").show();
    var ajax = $.ajax({
        url: 'Index',
        type: 'POST',
        success: function (data) {           
            $("#divLoading").hide();
            var box = bootbox.dialog({
                title: "Thêm mới cán bộ nghiệp vụ",
                message: data,
                onEscape: function () {
                    box.modal('hide');
                },
                buttons: {
                    success: {
                        label: "<i class='fa fa-plus-square-o'></i> Tạo mới",
                        className: "btn btn-sm btn-success",
                        callback: function () {                            
                            var form = $('#frmDTV');
                            if (!form.valid()) {
                                return false;
                            }
                            $("#divLoading").show();                            
                            $.ajax({
                                url: 'Save',
                                headers: headers,
                                data: {
                                    ENUMERATOR_ID: $("#ENUMERATOR_ID").val(),
                                    ADM_CODE: $("#ADM_CODE").val(),
                                    ADM_UNIT_ID: $("#ADM_UNIT_ID").val(),
                                    GROUP_CODE_OLD: $("#GROUP_CODE_OLD").val(),
                                    FULL_NAME: $("#FULL_NAME").val(),
                                    USERNAME: $("#USERNAME").val(),
                                    GROUPCODE: $("#GROUPCODE").val(),
                                    EMAIL: $("#EMAIL").val(),
                                    DESCRIPTIONS: $("#DESCRIPTIONS").val()
                                },
                                dataType: 'json',
                                type: 'post',
                                success: function (result) {
                                    Layout.toastr("", "Tạo mới thành công");
                                },
                                complete: function () {
                                    resetSearchInfoToDefault();
                                    action(pageIndex, pageSize);
                                },
                                error: function (errorThrown) {//function(request, textStatus, errorThrown)  {
                                    alert(JSON.stringify(errorThrown));
                                    //alert(request.getAllResponseHeaders());
                                    //alert(request.getResponseHeader('WWW-Authenticate'));                                  
                                }
                            });

                        }
                    },
                    danger: {
                        label: "<i class='fa fa-reply'></i> Hủy bỏ",
                        className: "btn btn-md btn-default",//"btn-danger",
                        callback: function () {
                        }
                    }
                }
            });
        },
        complete: function () {
            setTimeout(function () {
                $("#FULL_NAME").focus();
            }, 500);
        },
        error: function (ex) {
            alert(JSON.stringify(ex));
        }
    });
    return false;
}

function onEdit(id) {
    //alert(JSON.stringify(headers));
    $("#divLoading").show();
    $.ajax({
        url: 'ViewDetail',
        data: {
            ENUMERATOR_ID: id
        },
        type: 'GET',
        success: function (data) {
            $("#divLoading").hide();
            var box = bootbox.dialog({
                title: "Cập nhật cán bộ nghiệp vụ",
                message: data,
                onEscape: function () {
                    box.modal('hide');
                },
                buttons: {
                    success: {
                        label: "<i class='fa fa-pencil-square-o' ></i> Sửa",
                        className: "btn btn-sm btn-success",
                        callback: function () {
                            var form = $('#frmEdit');
                            if (!form.valid()) {
                                return false;
                            }
                            $("#divLoading").show();
                            $.ajax({
                                url: 'SaveEdit',
                                headers: headers,
                                data: {
                                    ENUMERATOR_ID: $("#ENUMERATOR_ID").val(),
                                    ADM_CODE: $("#ADM_CODE").val(),
                                    ADM_UNIT_ID: $("#ADM_UNIT_ID").val(),
                                    GROUP_CODE_OLD: $("#GROUP_CODE_OLD").val(),
                                    FULL_NAME: $("#FULL_NAME").val(),
                                    USERNAME: $("#USERNAME").val(),
                                    GROUPCODE: $("#GROUPCODE").val(),
                                    EMAIL: $("#EMAIL").val(),
                                    DESCRIPTIONS: $("#DESCRIPTIONS").val()
                                },
                                dataType: 'json',
                                type: 'post',
                                success: function (result) {
                                    Layout.toastr("", "Sửa thành công");
                                    //$("#divLoading").hide();
                                },
                                complete: function () {
                                    resetSearchInfoToDefault();
                                    action(pageIndex, pageSize);                                   
                                },
                                error: function (ex) {
                                    alert(JSON.stringify(ex));
                                }
                            });
                        }
                    },
                    danger: {
                        label: "<i class='fa fa-reply'></i> Hủy bỏ",
                        className: "btn btn-md btn-default",//"btn-danger",
                        callback: function () {
                        }
                    }
                }
            });
        },
        complete: function () {
            $(".edit-hidden").hide();
            setTimeout(function () {
                $("#FULL_NAME").focus();
            }, 500);
        },
        error: function (ex) {
            alert(JSON.stringify(ex));
        }
    });
    return false;
}